package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Dialog;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.SeekBar;
import android.widget.TextView;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import VideoHandle.EpDraw;
import VideoHandle.EpEditor;
import VideoHandle.EpVideo;
import VideoHandle.OnEditorListener;
import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.StickerAdapter;
import flc.ast.bean.MyStickerBean;
import flc.ast.databinding.ActivityVideoDecalBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.TimeUtil;
import stark.common.basic.view.container.StkRelativeLayout;

public class VideoDecalActivity extends BaseAc<ActivityVideoDecalBinding> {

    public static String videoPath;
    private StickerAdapter stickerAdapter;
    private int videoWidth, videoHeight;
    private Dialog myTipDialog;
    private boolean isDecal = false;

    @Override
    protected int onCreate() {
        return R.layout.activity_video_decal;
    }

    @Override
    public void onBackPressed() {
        myTipDialog.show();
    }

    @Override
    protected void initView() {
        mDataBinding.ivVideoDecalBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivVideoPlay.setOnClickListener(this);
        mDataBinding.tvGenerate.setOnClickListener(this);
        mDataBinding.ivVideoDecalSave.setOnClickListener(this);
        mDataBinding.rvVideoDecalList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        stickerAdapter = new StickerAdapter();
        mDataBinding.rvVideoDecalList.setAdapter(stickerAdapter);
        stickerAdapter.setOnItemClickListener(this);
        //提示弹框
        tipDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivVideoPlay://播放/暂停
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.bofang00);
                    mDataBinding.videoView.pause();
                } else {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.zanting00);
                    mDataBinding.videoView.start();
                }
                break;
            case R.id.tvGenerate:
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.bofang00);
                    mDataBinding.videoView.pause();
                }
                mDataBinding.ivStickerViewDecal.setShowHelpToolFlag(false);
                decalVideo();
                break;
            case R.id.ivVideoDecalSave:
                if (!isDecal) {
                    ToastUtils.showShort(getString(R.string.please_generate));
                    return;
                }
                saveVideo();
                break;
            //提示弹框
            case R.id.tvDialogTipCancel://取消
                myTipDialog.dismiss();
                break;
            case R.id.tvDialogTipRight://确定
                myTipDialog.dismiss();
                finish();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        //设置贴纸
        Resources res = getResources();
        Bitmap bmp = BitmapFactory.decodeResource(res, stickerAdapter.getItem(position).getStickerImg());
        mDataBinding.ivStickerViewDecal.addBitImage(bmp);
    }

    @Override
    protected void initData() {
        if (TextUtils.isEmpty(videoPath)) return;
        setPlayer();
        setSticker();
        //贴纸数据
        List<MyStickerBean> listSticker = new ArrayList<>();
        listSticker.add(new MyStickerBean(R.drawable.bq1, R.drawable.bqq1, false));
        listSticker.add(new MyStickerBean(R.drawable.bq2, R.drawable.bqq2, false));
        listSticker.add(new MyStickerBean(R.drawable.bq3, R.drawable.bqq3, false));
        listSticker.add(new MyStickerBean(R.drawable.bq4, R.drawable.bqq4, false));
        listSticker.add(new MyStickerBean(R.drawable.bq5, R.drawable.bqq5, false));
        listSticker.add(new MyStickerBean(R.drawable.bq6, R.drawable.bqq6, false));
        listSticker.add(new MyStickerBean(R.drawable.bq7, R.drawable.bqq7, false));
        listSticker.add(new MyStickerBean(R.drawable.bq8, R.drawable.bqq8, false));
        listSticker.add(new MyStickerBean(R.drawable.bq9, R.drawable.bqq9, false));
        listSticker.add(new MyStickerBean(R.drawable.bq10, R.drawable.bqq10, false));
        listSticker.add(new MyStickerBean(R.drawable.bq11, R.drawable.bqq11, false));
        listSticker.add(new MyStickerBean(R.drawable.bq12, R.drawable.bqq12, false));
        listSticker.add(new MyStickerBean(R.drawable.bq13, R.drawable.bqq13, false));
        listSticker.add(new MyStickerBean(R.drawable.bq14, R.drawable.bqq14, false));
        listSticker.add(new MyStickerBean(R.drawable.bq15, R.drawable.bqq15, false));
        stickerAdapter.setList(listSticker);
    }

    //保存视频
    private void decalVideo() {
        RxUtil.create(new RxUtil.Callback<Boolean>() {
            private String imagePath;

            @Override
            public void doBackground(ObservableEmitter<Boolean> emitter) {
                Bitmap bitmap = ImageUtils.view2Bitmap(mDataBinding.ivStickerViewDecal);
                imagePath = FileUtil.generateFilePath(Content.myTemp, ".png");
                boolean save = ImageUtils.save(bitmap, imagePath, Bitmap.CompressFormat.PNG);
                emitter.onNext(save);
            }

            @Override
            public void accept(Boolean isSave) {
                if (isSave) {
                    EpDraw epDraw = new EpDraw(imagePath, 0, 0, videoWidth, videoHeight, false);
                    epDraw.setRotate(0);
                    String resultFile = FileUtil.generateFilePath(Content.myTemp, ".mp4");//保存到我的视频
                    EpVideo epVideo = new EpVideo(videoPath);
                    epVideo.addDraw(epDraw);
                    EpEditor.OutputOption outputOption = new EpEditor.OutputOption(resultFile);
                    EpEditor.exec(epVideo, outputOption, new OnEditorListener() {
                        @Override
                        public void onSuccess() {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    dismissDialog();
                                    isDecal = true;
                                    ToastUtils.showShort(R.string.generate_suc);
                                    videoPath = resultFile;
                                    //设置播放器
                                    mDataBinding.ivVideoPlay.setImageResource(R.drawable.zanting00);
                                    mDataBinding.videoView.setVideoPath(videoPath);
                                    mDataBinding.videoView.seekTo(1);
                                    mDataBinding.videoView.start();
                                    mDataBinding.ivStickerViewDecal.clear();
                                }
                            });
                        }

                        @Override
                        public void onFailure() {
                            dismissDialog();
                            ToastUtils.showShort(R.string.decal_def);
                        }

                        @Override
                        public void onProgress(float progress) {
                            float v = progress * 100;
                            if (v < 0) {
                                v = 0;
                            } else if (v > 100) {
                                v = 100;
                            }
                            showDialog(getString(R.string.decal_ing)
                                    + new DecimalFormat("#.0").format(v) + "%");
                        }
                    });
                }
            }
        });
    }

    //保存视频
    private void saveVideo() {
        showDialog(getString(R.string.save_video_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        FileP2pUtil.copyPrivateVideoToPublic(mContext, videoPath);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        dismissDialog();
                        ToastUtils.showShort(R.string.save_suc);
                        startActivity(HomeActivity.class);
                    }
                });
            }
        }, 1000);
    }

    //设置播放器
    private void setPlayer() {
        //设置播放器
        mDataBinding.videoView.setVideoPath(videoPath);
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {  // 播放完成的监听
                mDataBinding.ivVideoPlay.setImageResource(R.drawable.bofang00);
                mp.seekTo(1);
            }
        });
        //开始播放视频
        mDataBinding.ivVideoPlay.setImageResource(R.drawable.zanting00);
        mDataBinding.videoView.start();
    }


    @Override
    protected void onStop() {
        super.onStop();
        mDataBinding.ivVideoPlay.setImageResource(R.drawable.bofang00);
        mDataBinding.videoView.pause();
    }

    //设置贴纸
    private void setSticker() {
        // 获取videoView真实的宽高大小
        mDataBinding.videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                videoWidth = mp.getVideoWidth();
                videoHeight = mp.getVideoHeight();
            }
        });
        // 将stickerView的宽高大小设置成videoView一样的大小
        mDataBinding.videoView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                StkRelativeLayout.LayoutParams stickerLayoutParams = (StkRelativeLayout.LayoutParams) mDataBinding.ivStickerViewDecal.getLayoutParams();
                stickerLayoutParams.width = right - left;
                stickerLayoutParams.height = bottom - top;
                mDataBinding.ivStickerViewDecal.setLayoutParams(stickerLayoutParams);
            }
        });
    }

    //提示弹框
    private void tipDialog() {
        myTipDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_tip, null);
        myTipDialog.setContentView(inflate);
        myTipDialog.setCancelable(true);
        Window dialogWindow = myTipDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView cancel = inflate.findViewById(R.id.tvDialogTipCancel);
        TextView right = inflate.findViewById(R.id.tvDialogTipRight);
        cancel.setOnClickListener(this);
        right.setOnClickListener(this);
    }

}